<template>
  <div class="app-container">
    <el-steps :active="active" finish-status="success">
      <el-step title="还车验车"></el-step>
      <el-step title="订单换车"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <br>
    <template v-if="active == 0">
      <el-form ref="form" :model="form" :rules="rules" label-width="0px">
        <el-descriptions class="margin-top margin-bottom" :column="2" border>
          <el-descriptions-item label-class-name="my-descriptions-label" label="车辆油量">
            <el-form-item label="">
              <el-slider v-model="form.fuelCapacity" style="width: 72%;display: inline-block;margin: 0 20px" :max="16"
                         show-stops></el-slider>
              <div style="display: inline-block;overflow: hidden">{{ form.fuelCapacity }}/16</div>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" label="车辆公里数">
            <el-form-item label="">
              <el-input v-model="form.vehicleMileage" placeholder="请输入车辆公里数" style="width:220px;margin-right:15px"
                        @keyup.native="form.vehicleMileage = oninput(form.vehicleMileage, 4)"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" label="验车时间">
            <el-form-item>
              <el-date-picker v-model="form.takeAlsoTime" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                              value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期"
                              style="width:220px;margin-right:15px"></el-date-picker>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" label="车辆随车物品">
            <el-form-item>
              <el-checkbox-group v-model="form.accessoryItems">
                <template v-for="item in dict.type.car_accessories">
                  <el-checkbox :key="item.id" :label="item.label" :value="item.value"></el-checkbox>
                </template>
              </el-checkbox-group>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="费用信息">
            <el-table :data="alsoCarItems" border>
              <el-table-column label="收费项名称">
                <template slot-scope="{ row }">
                  <el-input v-model="row.deductionsFor"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="扣款金额">
                <template slot-scope="{row}">
                  <el-input v-model="row.deductionsAmount" placeholder="请输入金额"
                            @keyup.native="row.deductionsAmount = oninput(row.deductionsAmount, 2)"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="{ row }">
                  <el-button type="danger" icon="el-icon-delete" size="mini"
                             @click="deleteChargingItems(row)"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-col :span="24" style="text-align: center">
              <el-button icon="el-icon-plus" @click="addChargingItems">添加收费项</el-button>
            </el-col>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="车身照片">
            <ImageUpload isArray v-model="form.bodyImage" :isShowTip="false" :limit="10"></ImageUpload>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="仪表盘/油表">
            <ImageUpload isArray v-model="form.panelImage" :isShowTip="false" :limit="10"></ImageUpload>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="内饰照片">
            <ImageUpload isArray v-model="form.interiorImage" :isShowTip="false" :limit="10"></ImageUpload>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="车辆划痕">
            <ImageUpload isArray v-model="form.scratchImage" :isShowTip="false" :limit="10"></ImageUpload>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="验车视频">
            <ImageUpload isArray v-model="form.videoUrls" :isVideo="true" :isShowTip="false" :limit="1">
            </ImageUpload>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="客户签名">
            <ImageUpload isArray v-model="form.signImage" :isShowTip="false" :limit="10"></ImageUpload>
          </el-descriptions-item>

          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="其他描述">
            <el-form-item>
              <el-input v-model="form.remark" type="textarea" placeholder="请输入其他描述" maxlength="200"
                        show-word-limit></el-input>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>
      <div class="footer " style="position: fixed;bottom: 50px;right: 50px;">
        <el-button @click="handleJiaocheyanchelist()">交车验车单</el-button>
        <el-button style="margin-top: 12px;" @click="next()">下一步</el-button>
        <el-button @click="closeDiolog">取消</el-button>
      </div>
    </template>
    <template v-if="active == 1">

      <el-form :model="changeCarData" label-width="160px" label-position="right" size="small" ref="MmvAddForm" inline>
        <el-row :gutter="15">
            <el-col :span="24">
              <MmvTitle title="车辆信息"></MmvTitle>
            </el-col>
            <el-col :span="8">
              <el-form-item label="更换车辆">
                <div style="display: flex;align-items: center;">
                  <el-input :value="carNo" placeholder="请选择车辆" @click.native="showpeiche = true" clearable readonly>
                    <el-button icon="el-icon-search" slot="append"></el-button>
                  </el-input>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="订单号">
                <div style="display: flex;width: 100%">
                  <div style="width: 200px;flex: 1">
                    <el-switch v-model="addOrSub" active-text="自定义" inactive-text="系统生成" :active-value='2' :inactive-value='1'  @change="myOrderNo=null"></el-switch>
                  </div>
                  <div style="width: 200px;flex: 1">
                    <el-input v-model="myOrderNo" placeholder="自定义订单编号" v-if="addOrSub==2"></el-input>
                  </div>
                </div>
              </el-form-item>
            </el-col>
<!--          <el-col :span="8">-->
<!--            <el-form-item label="签署续租合同">-->
<!--              <el-switch v-model="form.openContract"></el-switch>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>

      </el-form>


      <el-dialog :title="'换车'" :visible.sync="showpeiche" width="1000px" destroy-on-close append-to-body @close="showpeiche = false">
        <MmvPeiche ref="MmvPeiche" v-if="showpeiche" :modelId="detail.orderInfo.modelId" :storeId="detail.orderInfo.takeStoreId"
                   :orderStartTime="form.takeAlsoTime" :orderEndTime="detail.orderInfo.rentalEndTime" @close="peiche"></MmvPeiche>
        <div slot="footer">
          <el-button @click="showpeiche = false">关闭</el-button>
        </div>
      </el-dialog>

      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">
            <MmvTitle title="订单信息"></MmvTitle>
          </template>
          <el-descriptions class="margin-top margin-bottom" :column="3" border>
            <el-descriptions-item label-class-name="my-descriptions-label" :span="3">
              <template slot="label"> 订单编号</template>
              {{ detail.orderInfo.orderNo }}
            </el-descriptions-item>

              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 预约租期（天）</template>
                {{ detail.orderInfo.leaseDays }}
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 已用租期（天）</template>
                {{ detail.liquidatedDamages.days }}
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 剩余租期（天）</template>
                {{ detail.orderInfo.leaseDays-detail.liquidatedDamages.days<0?0:detail.orderInfo.leaseDays-detail.liquidatedDamages.days }}
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 当前车型</template>
                {{ detail.orderInfo.actualModelName }}
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 当前车辆</template>
                {{ detail.orderInfo.carNo }}
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 交车时间</template>
                {{ detail.orderInfo.actualStartTime }}
              </el-descriptions-item>
            <template v-if="carId">
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 换车车型</template>
                {{ modelName }}
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 换车车辆</template>
                {{ carNo }}
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 换车时间</template>
                {{ formData.takeAlsoTime }}
              </el-descriptions-item>
            </template>
          </el-descriptions>

        </el-collapse-item>
        <template v-if="carId">
          <el-collapse-item name="2">
            <template slot="title">
              <MmvTitle title="原车费用信息"></MmvTitle>
            </template>
            <el-row>
              <el-table :data="rentItems" :span-method="objectSpanMethod" border>
                <el-table-column label="" align="center" prop="name" />
                <el-table-column label="收费项名称" align="center" prop="chargeProjectName" />
                <el-table-column label="单价" align="center" prop="unitPrice" />
                <el-table-column label="收费类型" align="center" prop="chargeItemsType">
                  <template slot-scope="{ row }">
                    <dict-tag :options="dict.type.charge_type" :value="row.chargeItemsType" />
                  </template>
                </el-table-column>
                <el-table-column label="数目" align="center" prop="number" />
                <el-table-column label="费用" align="center" prop="chargeMoney" />
                <el-table-column label="已使用费用" align="center" prop="usedMoney">
                  <template slot-scope="{ row }">
                    {{ row.usedMoney ? row.usedMoney.toFixed(2) : '0' }}
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="3">
            <template slot="title">
              <MmvTitle title="新车费用信息"></MmvTitle>
            </template>
            <el-row>
              <el-col :span="23" style="margin: 0px 80px 20px 40px" class="chargeItemsVo-input">
                <el-table :data="chargeItemsVo" border>
                  <el-table-column label="收费项名称" prop="chargeProjectName" align="center">
                    <template slot-scope="{ row }">
                      <el-input v-if="row.canEdit == 3" v-model="row.chargeProjectName"></el-input>
                      <span v-else> {{ row.chargeProjectName }} </span>
                    </template>
                  </el-table-column>

                  <el-table-column label="单价" prop="unitPrice" align="center">
                    <template slot-scope="{ row }">
                      <el-input v-model="row.unitPrice"
                                @keyup.native="row.unitPrice = oninput(row.unitPrice, 2); jisuanMoney(row)">
                        <el-button slot="append">元</el-button>
                      </el-input>
                    </template>
                  </el-table-column>

                  <el-table-column label="收费类型" prop="chargeItemsType" align="center">
                    <template slot-scope="{ row }">
                      <el-select v-if="row.canEdit == 3" v-model="row.chargeItemsType" clearable @change="changeType(row)">
                        <el-option label="按次" :value="1"></el-option>
                        <el-option label="按天" :value="2"></el-option>
                        <el-option label="按个" :value="6"></el-option>
                      </el-select>
                      <span v-else> {{ {1: '按次', 2: '按天', 3: '按里程', 6: '按个'}[Number(row.chargeItemsType)] }}</span>

                    </template>
                  </el-table-column>

                  <el-table-column label="数目" prop="number" align="center">
                    <template slot-scope="{ row }">
                      <span v-if="row.canEdit == 1"> {{ row.number }}</span>
                      <span v-else-if="row.chargeItemsType == 2"> {{ row.number }}</span>
                      <el-input v-else v-model="row.number"
                                @keyup.native="row.number = oninput(row.number, 0,row.upperLimitOfNumber>=0?row.upperLimitOfNumber:999999);jisuanMoney(row) "></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="费用" prop="chargeMoney" align="center">
                    <template slot-scope="{ row }">
                      {{ Number(row.chargeMoney).toFixed(2) }} 元
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center">
                    <template slot-scope="{ row }">
                      <el-button v-if="row.canEdit == 3" type="danger" icon="el-icon-delete" size="mini" @click="deleteChargingItems2(row)"></el-button>
                      <el-switch v-model="row.selected" v-if="row.canEdit == 2 &&row.isOptional == 1"></el-switch>

                      <span v-if="row.isRent == 1">
                              <el-popover placement="right" trigger="click">
                                <div class="ant-popover-inner-content">
                                  <div class="fee-detail-wrapper">
                                    <div class="day-item" v-for="(item, index) in planPriceVoList" :key="index">
                                      <div class="date-weekname">
                                        <div>{{ item.time }}</div>
                                        <div>{{ item.dateOfWeek }}</div>
                                      </div>
                                      <div class="price-color word-break">¥{{ item.price }}</div>
                                    </div>
                                  </div>
                                </div>
                                <el-button slot="reference" icon="el-icon-search" type="text">价格日历</el-button>
                              </el-popover>
                            </span>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>

              <el-col :span="24" style="text-align: center;margin-bottom: 10px">
                <el-button icon="el-icon-plus" @click="addChargingItems2">添加收费项</el-button>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="5">
            <template slot="title">
              <MmvTitle title="退款/补缴费用"></MmvTitle>
            </template>
            <el-descriptions class="margin-top margin-bottom" :column="4" border>
              <el-descriptions-item label-class-name="my-descriptions-label"  content-class-name="my-content">
                <template slot="label"> 原租金总额</template>
                ¥{{ oldRent }}元
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label" content-class-name="my-content">
                <template slot="label"> 已用租金</template>
                <el-input v-model="usedRent" @keyup.native="usedRent = oninput(usedRent, 2)" style="width: 280px"></el-input>
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label" content-class-name="my-content">
                <template slot="label"> 剩余租金</template>
                ¥{{ (oldRent - usedRent).toFixed(2) }}元
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label" content-class-name="my-content">
                <template slot="label"> 新车租金</template>
                ¥{{ rentTotal }}元
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label" content-class-name="my-content">
                <template slot="label"> 现租金总额</template>
                <el-input v-model="newRent"  @keyup.native="newRent = oninput(newRent, 2)" placeholder="现租金总额"></el-input>
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label" content-class-name="my-content">
                <template slot="label"> 已付租金</template>
                ¥<span style="font-weight: bold;color: red">{{ detail.paidRent }}</span>元
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label" content-class-name="my-content">
                <template slot="label"> 待付租金</template>
                ¥<span style="font-weight: bold;color: red">{{ unPaidRent }}</span>元
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label" content-class-name="my-content">
                <template slot="label"> 待退租金</template>
                ¥<span style="font-weight: bold;color: red">{{ refundedRent }}</span>元
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
        </template>
      </el-collapse>

      <div style="height: 100px;"></div>
      <div class="footer " style="position: fixed;bottom: 50px;right: 50px;">
        <el-button type="primary" :loading="submitBtnLoading" @click="submitData">确定</el-button>
        <el-button style="margin-top: 12px;" @click="active = 0">上一步</el-button>
        <el-button @click="closeDiolog">取消</el-button>
      </div>

    </template>

    <el-drawer title="交车验车单" :visible.sync="showjiaocheyanchelist" direction="rtl" size="30%">
      <MmvDeliveryList ref="MmvDeliveryList" v-if="showjiaocheyanchelist" :orderNo="orderNo" :type="1"></MmvDeliveryList>
    </el-drawer>

  </div>
</template>

<script>
import MmvTitle from '@/components/MmvUI/MmvTitle.vue';
import * as orderApi from "@/api/order";
import Template from "@/views/system/template";
import MmvDeliveryList from "@/views/order/orderBasic/delivery-detail";
import CustomContent from "@/components/custom/content";
import MemberDetail from "@/views/components/memberDetail";
import MmvPeiche from "@/views/order/orderBasic/pageche";
import {renewalFee} from "@/api/order";

export default {
  components: {
    Template,
    MmvPeiche,
    MmvTitle,
    MmvDeliveryList,
    MemberDetail
  },
  dicts: ['sys_pay_type', 'order_payStatus', 'charge_type', 'refund_type', 'sys_order_status', 'car_accessories'],
  // props: ['orderNo'],
  data() {
    return {
      orderNo: null,
      active: 0,
      nowId: null,
      activeNames: ['1', '5'],
      detail: {
        chargingItems: [],
        orderInfo: {},
        customerInfo: {},
        liquidatedDamages: {
          rent: 0
        },
      },
      showjiaocheyanchelist: false,

      showpeiche: false,
      changeCarData:{},
      carId:null,
      carNo:null,
      planId:null,
      modelId:null,
      modelName:null,
      myOrderNo:null,


      deductionRent: 0,
      // deductionDeposit:0,
      loading: true,
      btnLoadIng: false,
      url: "", // 支付凭证
      submitBtnLoading: false,

      addOrSub: 1,
      rent: 0,
      priceDifference: 0,
      btnloadIng: false,
      form: {
        // orderNo: '',//订单编号   必传
        type: 2,//类型(1交车验车,2还车验车)   必传
        fuelCapacity: '',//车辆油量
        vehicleMileage: '',//公里数
        accessoryItems: [],//车辆随车物品(逗号隔开)
        remark: '',//其他描述
        takeAlsoTime: this.parseTime(new Date()),//取还车时间
        lkosten: 0.0,//补充油费(还车验车)
        bodyImage: [], //车身照片
        panelImage: [],//仪表盘
        interiorImage: [], //内饰照片
        scratchImage: [],//车辆划痕
        videoUrls: [],//验车视频
        signImage: [],//客户签名
        openContract:false
      },
      rules: {
        fuelCapacity: [{
          required: true,
          message: '车辆油量不能为空',
          trigger: 'change'
        }, {
          pattern: /^[0-9]+(.[0-9]{1,2})?$/,
          message: '车辆油量数输入不正确',
          trigger: 'blur',
        }],
        vehicleMileage: [{
          required: true,
          message: '公里数不能为空',
          trigger: 'change'
        }, {
          pattern: /^[0-9]+(.[0-9]{1,2})?$/,
          message: '公里数输入不正确',
          trigger: 'blur',
        }],
        takeAlsoTime: [{
          required: true,
          message: '还车时间不能为空',
          trigger: 'change'
        }]
      },
      alsoCarItems: [], // 收费项列表

      rentItems: [],
      paidRent: 0,
      usedRent: 0,
      oldRent: 0,
      newRent: 0,
      showTips: false,


      chargeItemsVo: [],
      planPriceVoList: [],

    }
  },
  computed: {

    // 代付租金
    unPaidRent() {
      let total = Number(this.newRent) - Number(this.detail.paidRent)
      return total > 0 ? total.toFixed(2) : 0
    },

    // 待退租金
    refundedRent() {
      let total = Number(this.detail.paidRent) - Number(this.newRent)
      return total > 0 ? total.toFixed(2) : 0
    },

    // 优惠
    preferentialAmount() {
      let total = this.rentTotal - this.rent
      return total > 0 ? total.toFixed(2) : 0
    },
    // 租金合计
    rentTotal() {
      const arr = this.chargeItemsVo
      let total = 0
      arr.forEach((val) => {
        if (val.selected) {
          total += Number(val.chargeMoney)
        }
      })
      this.newRent = (Number(total) + Number(this.usedRent)).toFixed(2);
      total = total > 0 ? total.toFixed(2) : 0
      this.rent = total
      return total
    },
    rentToBeRefunded() {
      var r1, r2, m, n;
      try {
        r1 = this.detail.liquidatedDamages.rent.toString().split(".")[1].length;
      } catch (e) {
        r1 = 0;
      }
      try {
        r2 = this.deductionRent.toString().split(".")[1].length;
      } catch (e) {
        r2 = 0;
      }
      m = Math.pow(10, Math.max(r1, r2));
      //last modify by deeka
      //动态控制精度长度
      n = (r1 >= r2) ? r1 : r2;
      return ((this.detail.liquidatedDamages.rent * m - this.deductionRent * m) / m).toFixed(n);
    },
    // depositToBeRefunded() {
    //   return this.detail.liquidatedDamages.deposit-this.deductionDeposit;
    // }
    formData() {
      const formData = {
        orderNo: this.orderNo,//订单编号   必传
        type: 2,//类型(1交车验车,2还车验车)   必传
        fuelCapacity: this.form.fuelCapacity,//车辆油量
        vehicleMileage: this.form.vehicleMileage,//公里数
        accessoryItems: String(this.form.accessoryItems),//车辆随车物品(逗号隔开)
        remark: this.form.remark,//其他描述
        takeAlsoTime: this.form.takeAlsoTime,//取还车时间
        lkosten: this.form.lkosten,//补充油费(还车验车)
        bodyImage: this.form.bodyImage, //车身照片
        panelImage: this.form.panelImage,//仪表盘
        interiorImage: this.form.interiorImage, //内饰照片
        videoUrls: this.form.videoUrls,
        scratchImage: this.form.scratchImage,//车辆划痕

        signImage: this.form.signImage,//客户签名
      };
      formData.cost = this.alsoCarItems.map(val => {
        return {
          deductionsFor: val.deductionsFor,
          deductionsAmount: val.deductionsAmount,
          deductionsWay: val.deductionsWay,
        };
      });
      return formData;
    },
  },
  filters: {
    dateOfWeek(val) {
      return {
        1: '星期一',
        2: '星期二',
        3: '星期三',
        4: '星期四',
        5: '星期五',
        6: '星期六',
        7: '星期日',
      }[Number(val)] || '';
    },
    memberType(val) {
      return {
        1: '企业',
        2: '个人',
      }[Number(val)] || '';
    },
    memberSource(val) {
      return {
        1: '搜索',
        2: '分享',
        3: '扫码',
        4: '手动录入',
      }[Number(val)] || '';
    },
    imageUrl(url) {
      return process.env.VUE_APP_BASE_IMAGE_URL + url
    },
  },
  watch: {
    'formData.takeAlsoTime': function (val) {
      if (val) {
        this.costDetail();
      }
    },
  },
  mounted() {
    this.orderNo = this.$route.query.orderNo
    this.costDetail();
    this.getalsoCarItems();
  },
  methods: {


    addChargingItems2() {
      this.chargeItemsVo.push({
        chargeProjectName: '',
        unitPrice: 0,
        chargeItemsType: 1,
        chargeProjectCategory: 9,
        number: 1,
        canEdit: 3,
        chargeMoney: 0,
        selected: true
      })
    },
    deleteChargingItems2(row) {
      let _index = -1;
      this.chargeItemsVo.forEach((item, index) => {
        if (row.chargeProjectName == item.chargeProjectName && item.canEdit == 3) {
          _index = index
        }
      })
      this.chargeItemsVo.splice(_index, 1)
    },
    jisuanMoney(row) {
      let chargeMoney = (row.unitPrice * row.number)||0;
      if (row.upperLimitOfAmount!=null&&row.upperLimitOfAmount >= 0 && chargeMoney > row.upperLimitOfAmount) {
        row.chargeMoney = row.upperLimitOfAmount.toFixed(2);
      } else {
        row.chargeMoney = chargeMoney.toFixed(2);
      }
    },
    changeType(row) {
      if (row.chargeItemsType == 2) {
        row.number = this.detail.orderInfo.leaseDays-this.detail.liquidatedDamages.days
        row.chargeMoney = (row.unitPrice * row.number).toFixed(2)
      } else {
        row.number = 1
        row.chargeMoney = (row.unitPrice * row.number).toFixed(2)
      }
    },


    step() {
      if (this.active-- < 0) this.active = 0;
    },
    next() {
      if (!this.formData.vehicleMileage) {
        this.$message.error("公里数不能为空");
        return;
      }else if (!this.formData.takeAlsoTime) {
        this.$message.error("还车时间不能为空");
        return;
      }else{
        this.active = 1
      }
    },
    getalsoCarItems() {
      orderApi.alsoCarItems().then(response => {
        const data = response.data.filter(val => val.isAvailable == 1);
        this.alsoCarItems = data.map(val => {
          return {
            ...val,
            checked: false,
            deductionsFor: val.chargeItemsName,
            deductionsAmount: '',
            deductionsWay: '2',
          }
        })
      });
    },
    addChargingItems() {
      this.alsoCarItems.push({
        chargeItemsName: '',
        chargeItemsType: 1,
        deductionsAmount: 0,
        checked: false,
        deductionsFor: '',
        deductionsWay: '2',
        index: new Date().getTime(),
      })
    },
    deleteChargingItems(row) {
      const index = this.alsoCarItems.map(f => f.index).indexOf(row.index);
      this.alsoCarItems.splice(index, 1)
    },
    /** 交车验车单 */
    handleJiaocheyanchelist() {
      this.showjiaocheyanchelist = true
    },
    closeDiolog() {
      // 关闭页面
      this.$router.go(-1)
      this.$store.dispatch('tagsView/delView', this.$route)
    },

    peiche(data) {
      this.carId = data.carId
      this.carNo = data.carNo
      this.showpeiche = false
      let days = this.detail.orderInfo.leaseDays-this.detail.liquidatedDamages.days<0?0:this.detail.orderInfo.leaseDays-this.detail.liquidatedDamages.days;
      orderApi.changeFee({carId:this.carId,orderNo:this.orderNo,takeAlsoTime:this.form.takeAlsoTime,days:days,useDay:this.detail.orderInfo.leaseDays}).then(response => {
        this.planId = response.data.planId;
        this.modelId = response.data.modelId;
        this.modelName = response.data.modelName;

        const chargingItemsVoList = response.data?.chargingItemsVoList || []; // 上门 取车 还车 异店 费用
        const noMandatoryOtherCostList = response.data?.noMandatoryOtherCostList || []; // 其他费用—非必选
        this.planPriceVoList =response.data?.planPriceVoList||[]//价格日历
        let arr = [...chargingItemsVoList,...noMandatoryOtherCostList];
        this.chargeItemsVo=[];
        for (let item of arr){
          this.chargeItemsVo.push({
            ...item,
            selected:true
          })
        }
      });
    },
    costDetail() {
      orderApi.earlyReturnDetail({ orderNo: this.orderNo, takeAlsoTime: this.form.takeAlsoTime, type: 4 }).then(response => {
        this.detail = response.data || {};
        this.deductionRent = response.data.liquidatedDamages.damages;

        this.rentItems = response.data.rentItems;
        this.paidRent = response.data.paidRent;
        this.usedRent = response.data.usedRent;
        this.oldRent = response.data.oldRent;

        this.carId = null;
        this.carNo = null;
        //
        // this.rentItems.push({ name: "已使用费用总计", type: 2, usedMoney: this.usedRent })
        // this.rentItems.push({ name: "已付租金总计", type: 2, usedMoney: this.paidRent })
        // this.rentItems.push({ name: "剩余租金", type: 2, usedMoney: this.detail.liquidatedDamages.rent })

        this.detail.customerInfo.labelClassify = response.data.customerInfo.labelClassify.split(',')
        this.loading = false
      });
    },
    submitData() {
      if (!this.formData.vehicleMileage) {
        this.$message.error("公里数不能为空");
        return;
      }
      if (!this.formData.takeAlsoTime) {
        this.$message.error("还车时间不能为空");
        return;
      }
      if (!this.carId) {
        this.$message.error("更换车辆不能为空");
        return;
      }
      if (Number(this.newRent)<Number(this.usedRent)) {
        this.$message.error("现租金总额不能小于已用租金");
        return;
      }
      this.submitBtnLoading = true

     let chargeItemsVo = this.chargeItemsVo.filter(i => {
        return i.selected && i.number > 0
      })//收费项

      orderApi.changeCar({
        orderNo: this.orderNo,
        usedRent: this.usedRent,
        oldRent: this.oldRent,
        rentTotal: this.rentTotal,
        addOrSub: this.addOrSub,
        priceDifference: this.priceDifference,
        newRent: this.newRent,
        rentItems: this.rentItems,

        leaseDays: this.detail.orderInfo.leaseDays-this.detail.liquidatedDamages.days,
        planId: this.planId,
        modelInfo: this.modelName,
        modelId: this.modelId,
        carId: this.carId,
        carNo: this.carNo,
        myOrderNo: this.myOrderNo,
        planPriceVoList: this.planPriceVoList,

        chargeItemsVo :chargeItemsVo,
        ...this.formData
      }).then(response => {

        this.$message.success(response.msg);
        this.closeDiolog();
      }).finally(err => {
        this.submitBtnLoading = false
      });
    },
    getSummaries(param) {
      const {
        columns,
        data
      } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index === 1) {
          const values = data.map(item => Number(item[column.property]));
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 元';
        }
      });

      return sums;
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      let rowspan = this.rentItems.filter(item => {
        return item.type == 1
      }).length
      if (columnIndex === 0) {
        if (rowIndex === 0 && rowIndex < rowspan) {
          return {
            rowspan: rowspan,
            colspan: 1,
          }
        } else if (rowIndex > 0 && rowIndex < rowspan) {
          return {
            rowspan: 0,
            colspan: 0,
          }
        }
      }
      if (rowIndex >= rowspan) {
        if (columnIndex === 0) {
          return [1, 1]
        } else if (columnIndex === 6) {
          return [1, 6]
        } else if (columnIndex < 7) {
          return [0, 0]
        }
      }
    },

  },

}
</script>

<style scoped>
.fee-detail-wrapper {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  max-width: 420px;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-direction: row;
  flex-direction: row;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -webkit-box-pack: start;
  -ms-flex-pack: start;
  justify-content: flex-start;
  max-height: 400px;
  overflow-y: auto;
}

.day-item {
  width: 80px;
  text-align: center;
  margin-top: 10px;
}

.price-color {
  color: #ff8b26;
}

</style>
<style>
.mySwitch {
  margin-left: -20px;
.el-switch__label--left {
  position: relative;
  left: 75px;
  color: #fff;
  z-index: -1111;
  margin-right: 20px;
span {
  width: 40px;
}
}
.el-switch__label--right {
  position: relative;
  right: 65px;
  color: #fff;
  z-index: -1111;
span {
  display: inline-block;
  width: 40px;
}
}
.el-switch__core {
  width: 65px !important;
}
.el-switch__label--right.is-active {
  z-index: 10;
  color: #fff !important;
}
.el-switch__label--left.is-active {
  z-index: 10;
  color: #fff !important;
}
.el-switch__core {
  height: 24px !important;
  border-radius: 12px !important;
}
.el-switch__core:after {
  top: 3px;
  left: 5px;
}
.el-switch.is-checked .el-switch__core::after {
  margin-left: -20px;
}
}
</style>
